import * as types from '../constants/ActionTypes';
import Request from '../utils/request';
import CommonStorage from '../utils/CommonStorage';
import Base from '../utils/Base';

/* global host */

const fetchUserInfo = cb => (dispatch) => {
  Request.get({
    url: '/dealer/info',
    accept: 'text',
    success: async (data) => {
      console.log('fetchInfo:------- ', data);
      if (data) {
        const saler = data.saler;
        const dealer = data.dealer;
        const uid = saler.uid;
        const salerId = saler.id;
        const tpl = saler.tpl;
        const dealerId = dealer.id;
        const loaclUid = await CommonStorage.getStorage('uid');
        if (cb) {
          cb({
            result: 1,
            email: saler.email,
            storeName: dealer.name,
          });
        }
        if (loaclUid === 'NotFoundError' || loaclUid === 'ExpiredError' || loaclUid.value !== uid) {
          CommonStorage.saveStorage('uid', uid);
        }
        const loaclTpl = await CommonStorage.getStorage('tpl');
        if (loaclTpl === 'NotFoundError' || loaclTpl === 'ExpiredError' || loaclTpl.value !== tpl) {
          Base.tpl = tpl;
          CommonStorage.saveStorage('tpl', tpl);
        }
        const factory = await CommonStorage.getStorage('factoryId');
        if (factory === 'NotFoundError' || factory === 'ExpiredError' || factory.value !== saler.factory_id) {
          CommonStorage.saveStorage('factoryId', saler.factory_id);
        }
        const dealerNames = await CommonStorage.getStorage('dealerName');
        if (dealerNames === 'NotFoundError' || factory === 'ExpiredError' || dealerNames.value !== dealer.name) {
          CommonStorage.saveStorage('dealerName', dealer.name);
        }
        const salerNames = await CommonStorage.getStorage('salerName');
        if (salerNames === 'NotFoundError' || factory === 'ExpiredError' || salerNames.value !== saler.username) {
          CommonStorage.saveStorage('salerName', saler.username);
        }
        dispatch(getSalerAndDealer(data));
        Base.dealerId = dealerId;
        Base.salerId = salerId;
        CommonStorage.saveStorage('dealerId', dealerId);
        CommonStorage.saveStorage('salerId', salerId);
        Base.doCallback(cb);
      }
    },
    fail: (data) => {
      console.log('get userinfo fail: ', data);
      dispatch(getSalerAndDealer({}));
      if (cb) {
        cb({
          result: 0,
        });
      }
    },
    error: (error) => {
      console.log('get userinfo error: ', error);
      dispatch(getSalerAndDealer({}));
      if (cb) {
        cb({
          result: 0,
        });
      }
    },
  });
};

const getVfCode = random => (dispatch) => {
  Request.get({
    url: `/verify?t=${random}`,
    accept: 'text',
    success: () => {
      dispatch(receiveVerificationCode(`${host}/verify?t=${random}`));
    },
    fail: () => {
      dispatch(receiveVerificationCode(''));
    },
    error: () => {
      dispatch(receiveVerificationCode(''));
    },
  });
};

const postLoginData = (email, password, verify) => (dispatch) => {
  Request.post({
    url: '/dealer/login',
    data: {
      email,
      password,
      verify,
      ref: '2',
    },
    success: (data) => {
      const keys = data && Object.keys(data);
      if (keys.length) {
        if (parseInt(data.eno, 10) === 2) {
          dispatch(checkLogin(false, '验证码有误'));
        } else if (parseInt(data.eno, 10) === 3 || parseInt(data.eno, 10) === 4) {
          dispatch(checkLogin(false, '用户名或密码有误'));
        } else if (parseInt(data.eno, 10) === 5 || parseInt(data.eno, 10) === 6 ||
         parseInt(data.eno, 10) === 7) {
          dispatch(checkLogin(false, '账号不存在'));
        } else if (parseInt(data.eno, 10) === 1) {
          dispatch(checkLogin(false, '请求错误'));
        } else if (parseInt(data.eno, 10) === 8) {
          dispatch(checkLogin(false, '账号已在其他移动设备上登陆，账号已退出。'));
        }
        return;
      }
      dispatch(checkLogin(true, ''));
      // fetchUserInfo(() => dispatch(checkLogin(true, '')));
    },
    fail: () => {
      dispatch(checkLogin(false, '登录验证失败，请稍后再试!'));
    },
    error: () => {
      dispatch(checkLogin(false, '服务器开小猜了，请稍后再试!'));
    },
  });
};

const resetLogin = () => ({
  type: types.RESET_LOGIN,
});


const receiveVerificationCode = code => ({
  type: types.RECEIVE_VFCODE,
  code,
});

const checkLogin = (isLogin, errMessage) => ({
  type: types.CHECK_LOGIN,
  isLogin,
  errMessage,
});

const getSalerAndDealer = dealerInfo => ({
  type: types.GET_DEALER_INFO,
  dealerInfo,
});

export {
  fetchUserInfo,
  getVfCode,
  postLoginData,
  resetLogin,
};
